<?php
/**
 * Attachments Controller
 *
 * This file will take care of file uploads (with rich text editor integration).
 *
 * PHP version 5
 *
 * @category Controller
 * @package  Croogo
 * @version  1.0
 * @author   Fahad Ibnay Heylaal <contact@fahad19.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class AttachmentsController extends AppController {
/**
 * Controller name
 *
 * @var string
 * @access public
 */
    public $name = 'Attachments';
/**
 * Models used by the Controller
 *
 * @var array
 * @access public
 */
    public $uses = array('Attachment', 'Node');
/**
 * Helpers used by the Controller
 *
 * @var array
 * @access public
 */
    public $helpers = array('Filemanager', 'Text', 'Image');
/**
 * Node type
 *
 * If the Controller uses Node model,
 * this is, most of the time, the singular of the Controller name in lowercase.
 *
 * @var string
 * @access public
 */
    public $type = 'attachment';
/**
 * Uploads directory
 *
 * relative to the webroot.
 *
 * @var string
 * @access public
 */
    public $uploadsDir = 'uploads';

/**
 * Before executing controller actions
 *
 * @return void
 * @access public
 */
    public function beforeFilter() {
        parent::beforeFilter();

        // Comment, Category, Tag not needed
        $this->Node->unbindModel(array('hasMany' => array('Comment'), 'hasAndBelongsToMany' => array('Category', 'Tag')));
        
        $this->Node->Behaviors->attach('Tree', array('scope' => array('Node.type' => $this->type)));
       // $this->set('type', $this->type);
    }

/**
 * Admin index
 *
 * @return void
 * @access public
 */
    public function admin_index($nodeId = null) {	
	
	if (isset($this->data['Attachment']['node_id']) && is_numeric($this->data['Attachment']['node_id'])) {
	    $nodeId = $this->data['Attachment']['node_id'];
	}
	
	if (isset($this->params['named']['editor'])) {
            $this->layout = 'admin_full';
        }	
	
	$this->Node->contain();	
	$nodes = $this->Node->find('list');
	$nodes[0] = __('-- Unassociated --', true);
	
	$fileAttachments = $this->paginate('Attachment', array (
		'Attachment.node_id' => $nodeId,		
		'Attachment.type' => 0,		    
	    )
	);
	
	$imageAttachments = $this->paginate('Attachment', array (
		'Attachment.node_id' => $nodeId,
		'Attachment.type' => 1,
	    )
	);		
	
	$this->set('title_for_layout', __('Manage attachments', true));
	$this->set('nodeId', $nodeId);
	$this->set(compact('fileAttachments', 'imageAttachments', 'node', 'nodes'));
    }
        
/**
 * Admin add file
 *
 * @return void
 * @access public
 */
    public function admin_addFile() {
        $this->set('title_for_layout', __('Add file attachment', true));

        if (isset($this->params['named']['editor'])) {
            $this->layout = 'admin_full';
        }
	
	$params = '';	
	
        if (isset($this->params['named']['editor'])) {
            $params .= '/editor:1';
        }					
	
	if (isset($this->params['named']['image'])) {
            $params .= '/image:1';
        }
	
	$params .= '#manage-files';
	$redirect = array('action'=>'index', $this->data['Attachment']['node_id'], $params);	

        if (! empty($this->data)) {	    
	    //pr($this->data);
	    //die();
            $file = $this->data['Attachment']['filename'];
            unset($this->data['Attachment']['filename']);
	    
	    if (! is_dir(WWW_ROOT . $this->uploadsDir . DS . 'files')) {
		mkdir(WWW_ROOT . $this->uploadsDir . DS . 'files');
	    }

            // check if file with same path exists
            $destination = WWW_ROOT . $this->uploadsDir . DS . 'files' . DS . $file['name'];
            if (file_exists($destination)) {
                $newFileName = String::uuid() . '-' . $file['name'];
                $destination = WWW_ROOT . $this->uploadsDir . DS . 'files' . DS . $newFileName;
            } else {
                $newFileName = $file['name'];
            }

            // remove the extension for title
            if (explode('.', $file['name']) > 0) {
                $fileTitleE = explode('.', $file['name']);
                array_pop($fileTitleE);
                $fileTitle = implode('.', $fileTitleE);
            } else {
                $fileTitle = $file['name'];
            }

            $this->data['Attachment']['type'] = $this->Node->Attachment->types['FILE'];
	    $this->data['Attachment']['title'] = $fileTitle;
	    $this->data['Attachment']['filename'] = $newFileName;
	    $this->data['Attachment']['mime_type'] = $file['type'];	    
	    $this->data['Attachment']['size'] = $file['size'];	    

            $this->Attachment->create();
            if ($this->Attachment->save($this->data)) {
                // move the file
                move_uploaded_file($file['tmp_name'], $destination);
                $this->Session->setFlash(__('The Attachment has been saved', true), 'default', array('class' => 'success'));		
            } else {
                $this->Session->setFlash(__('The Attachment could not be saved. Please, try again.', true), 'default', array('class' => 'error'));		
            }
        }
	
	$this->redirect($redirect);
    }
    
/**
 * Admin add file
 *
 * @return void
 * @access public
 */
    public function admin_addImage() {
        $this->set('title_for_layout', __('Add Image attachment', true));
;
	if (isset($this->params['named']['editor'])) {
            $this->layout = 'admin_full';
        }
	
	$params = '';	
	
        if (isset($this->params['named']['editor'])) {
            $params .= '/editor:1';
        }					
	
	if (isset($this->params['named']['image'])) {
            $params .= '/image:1';
        }
	
	$params .= '#manage-images';
	$redirect = array('action'=>'index', $this->data['Attachment']['node_id'], $params);

        if (!empty($this->data)) {	    
	    //pr($this->data);
	    //die();
            $file = $this->data['Attachment']['filename'];
            unset($this->data['Attachment']['filename']);	    
	    
	    App::import('Lib', 'cwImage');
	    $cwImage = new cwImage();
	    $bImageLoaded = false;
	    try {
		$bImageLoaded = $cwImage->load($file['tmp_name']);
	    } catch (Exception $e) {
		$this->Session->setFlash(__(sprintf("An error occurred while loading the image:\n%s", $e->getMessage()), true), 'default', array('class' => 'error'));
		$this->redirect($redirect);
	    }
	    
	    if ($bImageLoaded) {
		$resizedImage = $cwImage->resize(
			    null,
			    array (
				'width' => Configure::read('Image.width'),
				'height' => Configure::read('Image.height')
			    ),
			    array (
				'exactSize' => false,
				'resizeSmaller' => false
			    )
			);


		if (! is_dir(WWW_ROOT . $this->uploadsDir . DS . 'images')) {
		    mkdir(WWW_ROOT . $this->uploadsDir . DS . 'images');
		}

		// check if file with same path exists
		$destination = WWW_ROOT . $this->uploadsDir . DS . 'images' . DS . $resizedImage->changeExtension($file['name'], '.jpg');
		if (file_exists($destination)) {
		    $newFileName = String::uuid() . '-' . $resizedImage->changeExtension($file['name'], '.jpg');
		    $destination = WWW_ROOT . $this->uploadsDir . DS . 'images' . DS . $newFileName;
		} else {
		    $newFileName = $resizedImage->changeExtension($file['name'], '.jpg');
		}
			    
		// remove the extension for title
		$fileTitle = $resizedImage->changeExtension($file['name']);            
		
		if ($resizedImage->save($destination)) {		
		    
		    $this->data['Attachment']['type'] = $this->Node->Attachment->types['IMAGE'];
		    if (empty($this->data['Attachment']['title'])) {
			$this->data['Attachment']['title'] = $fileTitle;
		    }
		    $this->data['Attachment']['filename'] = $newFileName;
		    $this->data['Attachment']['mime_type'] = 'image/jpeg';	    
		    $this->data['Attachment']['size'] = filesize($destination);

		    $this->Attachment->create();		    
		    
		    if ($this->Attachment->save($this->data)) {
			$this->Session->setFlash(__('The image attachment has been saved', true), 'default', array('class' => 'success'));
		    } else {
			$this->Attachment->delete();
			$this->Session->setFlash(__('The image attachment could not be saved. Please, try again.', true), 'default', array('class' => 'error'));
		    }

		} else {
		    $this->Session->setFlash(__('The Attachment could not be saved. Please, try again.', true), 'default', array('class' => 'error'));		    
		}		
	    } else {
		$this->Session->setFlash(__('Could not load the image. Please, try again.', true), 'default', array('class' => 'error'));		
	    }
	    	    
        }
	$this->redirect($redirect);
    }
    
/**
 * Admin edit
 *
 * @param int $id 
 * @return void
 * @access public
 */
    public function admin_edit($id = null) {
        $this->set('title_for_layout', __('Edit Attachment', true));

        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid Attachment', true), 'default', array('class' => 'error'));
            $this->redirect(array('action'=>'index'));
        }
        if (!empty($this->data)) {
            if ($this->Node->save($this->data)) {
                $this->Session->setFlash(__('The Attachment has been saved', true), 'default', array('class' => 'success'));
                $this->redirect(array('action'=>'index'));
            } else {
                $this->Session->setFlash(__('The Attachment could not be saved. Please, try again.', true), 'default', array('class' => 'error'));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Node->read(null, $id);
        }
    }

/**
 * Admin delete
 *
 * @param int $id 
 * @return void
 * @access public
 */
    public function admin_delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for Attachment', true), 'default', array('class' => 'error'));
            $this->redirect(array('action'=>'index', $id));
        }
        if (!isset($this->params['named']['token']) || ($this->params['named']['token'] != $this->params['_Token']['key'])) {
            $blackHoleCallback = $this->Security->blackHoleCallback;
            $this->$blackHoleCallback();
        }

	try {
	    $result = $this->Attachment->delete($id);
	} catch (Exception $e) {
	    $this->Session->setFlash($e->getMessage(), 'default', array('class' => 'error'));
	    $this->redirect($this->referer());
	}

	if ($result) {
	    $this->Session->setFlash(__('Attachment deleted', true), 'default', array('class' => 'success'));	    
	} else {
	    $this->Session->setFlash(__('Could not delete the specified attachment', true), 'default', array('class' => 'error'));	    
	}
	
	$this->redirect($this->referer());
	
    }
    
/**
 * Admin browse
 */    

    public function admin_browse($nodeId = null) {
        $this->layout = 'admin_full';
        $this->admin_index($nodeId);
    }

}
?>